package com.aidisp.util;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MailUtil {

	private static class EmailAuthenticator extends Authenticator {
		private String userName;
		private String password;
		EmailAuthenticator(String userName,String password){
			this.userName = userName;
			this.password = password;
		}
		public PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(userName, password);
		}
	}
	/**
	 * 
	 * @param smtp		smtp服务器地址
	 * @param sender	邮件发送者
	 * @param subject	邮件标题
	 * @param content	邮件内容
	 * @param userName	smtp服务名
	 * @param password	smtp密码
	 * @param from		发送者email地址
	 * @param to		接收者email地址
	 */
	public static void sendMail(String smtp,String port,String sender,String subject,String content,String userName,String password,String from,String to){
		Properties props = new Properties();
		Authenticator auth = new EmailAuthenticator(userName,password);
		props.put("mail.smtp.host", smtp);
		props.put("mail.smtp.auth", "true");
		if(port!=null&&!"".equals(port)){
			props.setProperty("mail.smtp.port", port);
		}
		Session session = Session.getDefaultInstance(props, auth);
		MimeMessage message = new MimeMessage(session);
		try {
			message.setSubject(subject);
			message.setText(content);
			message.setSentDate(new Date());
			Address fromAddress = new InternetAddress(from, sender);
			message.setFrom(fromAddress);
			Address toAddress = new InternetAddress(to);
			message.addRecipient(Message.RecipientType.TO, toAddress);
			Transport.send(message);
		} catch (MessagingException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	public static void sendMail(String userEmail,String content){
		String smtp = "smtp.163.com";
		String sender = "周训游";
		String subject = "主题";
		String userName = "ZhouXunYou@163.com";
		String password = "MFKykIYTB982&#!";
		String from = "zhouxunyou@163.com";
		String port = "25";
		sendMail(smtp, port,sender, subject, content, userName, password, from, userEmail);
	}
	public static void main(String[] args) {
		sendMail("zhouxunyou@feinno.com","xxxxx");
	}
}
